package com.example.icongyou.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.icongyou.R;
import com.example.icongyou.api.ApiService;
import com.example.icongyou.bean.AbilityDimension;
import com.example.icongyou.bean.ApiResponse;
import com.example.icongyou.bean.PersonalSummary;
import com.example.icongyou.bean.TaskStats;
import com.example.icongyou.retrofit.RetrofitClient;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 个人数据看板碎片：展示总得分、总排名、能力维度、任务进度
 */
public class PersonalDashboardFragment extends Fragment {

    // 控件声明
    private TextView tvTotalScore;
    private TextView tvOverallRank;
    private TextView tvCompletedTasks;
    private TextView tvPendingTasks;
    private TextView tvCompletionRate;
    private LinearLayout llAbilities;
    private ProgressBar progressLoading;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载布局文件
        View view = inflater.inflate(R.layout.fragment_personal_dashboard, container, false);
        // 初始化控件
        initViews(view);
        // 加载数据（模拟+后续可替换为网络请求）
        loadPersonalData();
        return view;
    }

    /**
     * 初始化所有控件
     */
    private void initViews(View view) {
        tvTotalScore = view.findViewById(R.id.tv_total_score);
        tvOverallRank = view.findViewById(R.id.tv_overall_rank);
        tvCompletedTasks = view.findViewById(R.id.tv_completed_tasks);
        tvPendingTasks = view.findViewById(R.id.tv_pending_tasks);
        tvCompletionRate = view.findViewById(R.id.tv_completion_rate);
        llAbilities = view.findViewById(R.id.ll_abilities);
        progressLoading = view.findViewById(R.id.progress_loading); // 需在布局中添加ProgressBar
    }

    /**
     * 加载个人数据（模拟网络请求延迟）
     */
    private void loadPersonalData() {
        showLoading(); // 显示加载动画
        // 获取当前登录学生ID（实际应从登录信息中获取，此处为示例）
        String studentId = "student_1";

        // 创建ApiService实例（根据你的项目结构调整）
        ApiService apiService = RetrofitClient.getApiService();
        Call<ApiResponse<PersonalSummary>> call = apiService.getPersonalSummary(studentId);

        call.enqueue(new Callback<ApiResponse<PersonalSummary>>() {
            @Override
            public void onResponse(Call<ApiResponse<PersonalSummary>> call, Response<ApiResponse<PersonalSummary>> response) {
                hideLoading(); // 隐藏加载动画
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<PersonalSummary> apiResponse = response.body();
                    if (apiResponse.isSuccess()) { // 使用ApiResponse的isSuccess()判断
                        updatePersonalUI(apiResponse.getData());
                    } else {
                        Toast.makeText(getContext(), "数据错误: " + apiResponse.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "接口请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<PersonalSummary>> call, Throwable t) {
                hideLoading(); // 隐藏加载动画
                Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void showLoading() {
        progressLoading.setVisibility(View.VISIBLE);
        // 可同时隐藏其他内容布局
    }

    private void hideLoading() {
        progressLoading.setVisibility(View.GONE);
    }
    /**
     * 根据数据更新个人看板UI
     */
    private void updatePersonalUI(PersonalSummary summary) {
        if (summary == null) {
            Toast.makeText(getContext(), "数据加载失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 1. 更新总分和总排名
        tvTotalScore.setText(String.format("%.1f", summary.getTotalScore()));
        tvOverallRank.setText(String.format("第%d名", summary.getOverallRank()));

        // 2. 更新任务进度
        TaskStats taskStats = summary.getTaskStats();
        tvCompletedTasks.setText(String.valueOf(taskStats.getCompletedTasks()));
        tvPendingTasks.setText(String.valueOf(taskStats.getPendingTasks()));
        tvCompletionRate.setText(String.format("%.0f%%", taskStats.getCompletionRate()));

        // 3. 动态添加能力维度（循环创建进度条项）
        List<AbilityDimension> abilities = summary.getAbilityDimensions();
        // 兼容可能的空数据
        if (abilities == null) {
            abilities = new ArrayList<>();
        }
        llAbilities.removeAllViews(); // 清空原有视图，避免重复
        for (AbilityDimension ability : abilities) {
            // 加载能力维度子项布局
            View abilityItem = LayoutInflater.from(getContext())
                    .inflate(R.layout.item_ability_dimension, llAbilities, false);

            // 绑定子项控件
            TextView tvDimensionName = abilityItem.findViewById(R.id.tv_dimension_name);
            ProgressBar pbAchievement = abilityItem.findViewById(R.id.pb_achievement);
            TextView tvAchievementRate = abilityItem.findViewById(R.id.tv_achievement_rate);

            // 设置数据（增加非空判断，避免空指针）
            if (ability != null) {
                tvDimensionName.setText(ability.getDimensionName() != null ? ability.getDimensionName() : "未知维度");
                pbAchievement.setProgress((int) (ability.getAchievementRate() >= 0 ? ability.getAchievementRate() : 0));
                tvAchievementRate.setText(String.format("%.0f%%", ability.getAchievementRate() >= 0 ? ability.getAchievementRate() : 0));
            }

            // 添加到父布局
            llAbilities.addView(abilityItem);
        }
    }
}